package com.sharelogindemo;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class ForgetPasswordActivity extends BaseActivity {
    private EditText mEditPhone;
    private EditText mEditCode;
    private EditText mEditPassword;
    private Button mButtonSubmit;
    private CountDownTimerButton mCountDownTimerButton;
    private TextView mTextTitle;
    private ImageView account_password_status;
    private LinearLayout mLayoutPhone;
    private LinearLayout mLayoutCode;
    private ImageView mImagePhone;
    private String Number;
    private ProgressDialog mDialog;
    private boolean isHiddenPassword = true;
    /**
     * 短信验证的回调监听
     */
    private EventHandler ev = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) {
                switch (event) {
                    case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE: //服务端验证成功
                        HashMap<String, Object> mData = (HashMap<String, Object>) data;
                        String phone = (String) mData.get("phone");
                        if (phone.equals(Number)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showDailog("恭喜你！通过验证");
                                    mDialog.dismiss();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showDailog("验证失败");
                                    mDialog.dismiss();
                                }
                            });
                        }
                        break;
                    case SMSSDK.EVENT_GET_VERIFICATION_CODE:
                        break;
                }

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        initView();
        SMSSDK.registerEventHandler(ev);
    }

    private void initView() {
        mImagePhone = (ImageView) findViewById(R.id.forget_phone_image);
        mLayoutPhone = (LinearLayout) findViewById(R.id.forget_phone_layout);
        mLayoutCode = (LinearLayout) findViewById(R.id.forget_code_layout);
        mEditPhone = (EditText) findViewById(R.id.forget_phone);
        mEditCode = (EditText) findViewById(R.id.forget_code);
        mEditPassword = (EditText) findViewById(R.id.forget_password);
        mButtonSubmit = (Button) findViewById(R.id.forget_submit);
        mTextTitle = (TextView) findViewById(R.id.title);
        back_layout = (LinearLayout) findViewById(R.id.back_layout);
        mCountDownTimerButton = (CountDownTimerButton) findViewById(R.id.forget_get_sms_code);

        mButtonSubmit.setClickable(false);
        mCountDownTimerButton.setEnabled(false);
        mTextTitle.setText(R.string.forget_password1);
        back_layout.setOnClickListener(this);
        mButtonSubmit.setOnClickListener(this);
        mLayoutCode.setOnClickListener(this);
        mCountDownTimerButton.setOnClickListener(this);
        Utils.setSelection(ForgetPasswordActivity.this, mEditPhone, false);

        mEditPhone.addTextChangedListener(new AddTextChangeListener());
        mEditCode.addTextChangedListener(new AddTextChangeListener());
        mEditPassword.addTextChangedListener(new AddTextChangeListener());
        account_password_status = (ImageView) findViewById(R.id.forget_account_password_status);
        account_password_status.setOnClickListener(this);
        mEditPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mLayoutPhone.setBackgroundResource(R.mipmap.account_line_nor);
                    mImagePhone.setBackgroundResource(R.mipmap.account_icon_phone_sel);
                } else {
                    mLayoutPhone.setBackgroundResource(R.mipmap.account_line_sel);
                    mImagePhone.setBackgroundResource(R.mipmap.account_icon_phone);
                }
            }
        });
    }

    private class AddTextChangeListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String mAccount = mEditPhone.getText().toString();
            String mPassword = mEditPassword.getText().toString();
            String mCode = mEditCode.getText().toString();
            if (Utils.isPhoneNumberValid(mAccount, Utils.COUNTRY_CHINA_CODE, false) && Utils.isCodeNumber(mCode) && Utils.isPasswordNumber(mPassword)) {
                mButtonSubmit.setBackgroundResource(R.drawable.account_login_bg);
                mButtonSubmit.setClickable(true);
            } else {
                mButtonSubmit.setBackgroundResource(R.drawable.account_no_login_bg);
                mButtonSubmit.setClickable(false);
            }
            if (mEditPassword.isFocused()) {// 防止用户输入特殊字符
                if (!Utils.isPasswordNumber1(mPassword, mEditPassword)) {
                    ToastUtil.showToast(ForgetPasswordActivity.this, R.string.is_password);
                }
            }
            if(!mCountDownTimerButton.isEnabled()&&!mCountDownTimerButton.isTimeing()){
                changeGetCodeView();
            }
        }


        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private void changeGetCodeView() {
        if (Utils.isPhoneNumberValid(mEditPhone.getText().toString(), Utils.COUNTRY_CHINA_CODE, false)) {
            mCountDownTimerButton.setEnabled(true);
            mCountDownTimerButton.setBackground(getResources().getDrawable(R.drawable.background_normal));
        } else {
            mCountDownTimerButton.setEnabled(false);
            mCountDownTimerButton.setBackground(getResources().getDrawable(R.drawable.background_disable));
        }
    }

    private void showDailog(String text) {
        new AlertDialog.Builder(ForgetPasswordActivity.this)
                .setTitle(text)
                .setPositiveButton("确定", null)
                .show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.forget_get_sms_code:
                Utils.setSelection(ForgetPasswordActivity.this, mEditCode, false);
                getSecurity();
                break;
            case R.id.forget_submit:
                doForgetPassword();
                break;
            case R.id.forget_account_password_status:
                if (isHiddenPassword) {
                    mEditPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    account_password_status.setBackgroundResource(R.mipmap.account_btn_show_nor);
                } else {
                    mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    account_password_status.setBackgroundResource(R.mipmap.account_btn_show_sel);
                }
                isHiddenPassword = !isHiddenPassword;
                mEditPassword.postInvalidate();
                //切换后将EditText光标置于末尾
                CharSequence charSequence = mEditPassword.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
                break;
        }
    }

    /**
     * 获取验证码
     */

    private void getSecurity() {
        Number = mEditPhone.getText().toString();
        Utils.setSelection(ForgetPasswordActivity.this, mEditCode, false);
        SMSSDK.getVerificationCode("+86", Number);
        mCountDownTimerButton.startCountDown();
    }


    private void doForgetPassword() {
        SMSSDK.submitVerificationCode("+86", Number, mEditCode.getText().toString());
        mDialog = ProgressDialog.show(this, null, "正在验证...", false, true);
    }

}
